package blog.utils;

import io.jsonwebtoken.*;
import org.joda.time.DateTime;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {

    private static final String SECRET = "123456@$$";  // 给token加密的秘钥

    // 创建token
    public static String createToken(Long userId) {
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);

        JwtBuilder jwtBuilder = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(new DateTime().getMillis() + 24 * 60 * 60 * 1000));

        String token = jwtBuilder.compact();

        return token;
    }

    // 验证token
    public static Map<String, Object> checkToken(String token) { // 要么返回正常用户信息，要么报异常

        try {
            Jwt parse = Jwts.parser().setSigningKey(SECRET).parse(token);

            return (Map<String, Object>) parse.getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    // 测试
    public static void main(String[] args) {

        String token = JwtUtils.createToken(413977414L);

        System.out.println(token);

        Map<String, Object> map =  JwtUtils.checkToken(token);

        System.out.println(map);

    }
}
